import { useStore, Store } from 'vuex';
import { SET_USER_LOCAL_LABEL } from '@/store/actionType';
import md5 from '@/utils/md5';
import RESTURL from '@/http/http.restUrl';


const LOCAL_LABEL_PREFIX : string = 'XIAOLV_YC_USERLABEL';

const SAVE_STATE_KEYS : string[] = ['userInfo','version','baseUrl'];


interface IUseUserData {
	getUserInfo : (userId : number) => void;
	setUserLocalLabel : (userId : number) => void;
	updateUserInfo : () => Promise<IUserInfo>;
	LOCAL_LABEL_PREFIX : string;
	SAVE_STATE_KEYS : string[];
}

function useUserData() : IUseUserData {
	const store : Store<any> = useStore();


	const getUserInfo = async (userId : number) : Promise<IUserInfo> => {
			const userInfo : IUserInfo = (await uni.http.POST(RESTURL.getUserInfo, {
				customer_id: userId,
			})).data;
			uni.store.set('userInfo', userInfo);
			return userInfo
	}
	const setUserLocalLabel = (userId : number) : void => {
		const userLocalLabel = md5.md5(`${LOCAL_LABEL_PREFIX}${userId}`);
		uni.setStorageSync(LOCAL_LABEL_PREFIX, userLocalLabel);
	}

	const updateUserInfo = async () : Promise<IUserInfo> => {
		const userInfo : IUserInfo = (await uni.http.POST(RESTURL.getUserInfo, {
			customer_id: store.state.userInfo.id,
		})).data;
		uni.store.local('userInfo', userInfo);
		return userInfo
	}


	return {
		getUserInfo,
		setUserLocalLabel,
		LOCAL_LABEL_PREFIX,
		SAVE_STATE_KEYS, 
		updateUserInfo
	}
}

export {
	useUserData
};